package com.tlgen.orm.utils.log;

import com.tlgen.orm.components.dataSource.DataSourceContextHolder;

import java.util.List;

public class ColorLogger {

    // ANSI 颜色代码
    public static final String RESET = "\033[0m";
    public static final String BLACK = "\033[0;30m";
    public static final String RED = "\033[0;31m";
    public static final String GREEN = "\033[0;32m";
    public static final String YELLOW = "\033[0;33m";
    public static final String BLUE = "\033[0;34m";
    public static final String PURPLE = "\033[0;35m";
    public static final String CYAN = "\033[0;36m";
    public static final String WHITE = "\033[0;37m";

    // 加粗和背景色
    public static final String GREEN_BOLD_BRIGHT = "\033[1;92m";
    public static final String BLUE_BOLD_BRIGHT = "\033[1;94m";
    public static final String PURPLE_BACKGROUND = "\033[45m";
    public static final String CYAN_BACKGROUND_BRIGHT = "\033[0;106m";

    // 表情符号集合
    public static final String ROCKET = "🚀";
    public static final String CHECK = "✅";
    public static final String GEAR = "⚙️";
    public static final String LIGHTNING = "⚡";
    public static final String LOCK = "🔒";
    public static final String FIRE = "🔥";
    public static final String STAR = "⭐";
    public static final String COMPUTER = "💻";

    // 日志样式模板
    public static final String SUCCESS_STYLE = GREEN_BOLD_BRIGHT + "✨ %s %s" + RESET;
    public static final String INFO_STYLE = BLUE_BOLD_BRIGHT + "ℹ️ %s %s" + RESET;
    public static final String HIGHLIGHT_STYLE = PURPLE + "🌟 %s %s" + RESET;

    // 特殊消息格式
    public static void printColorfulBanner(String message) {
        String banner = BLUE_BOLD_BRIGHT + "======================================" + RESET + "\n"
                + CYAN_BACKGROUND_BRIGHT + BLACK + " " + message + " " + RESET + "\n"
                + BLUE_BOLD_BRIGHT + "======================================" + RESET;
        System.out.println(banner);
    }

    public static void printSuccessMessage(String message) {
        System.out.printf((SUCCESS_STYLE) + "%n", CHECK, message);
    }

    public static void printInfoMessage(String message) {
        System.out.printf((INFO_STYLE) + "%n", GEAR, message);
    }

    public static void printHighlightMessage(String message) {
        System.out.printf((HIGHLIGHT_STYLE) + "%n", STAR, message);
    }

    // 自定义彩色输出
    public static void printColored(String color, String emoji, String message) {
        System.out.println(color + emoji + " " + message + RESET);
    }

    // ================== VSCode 风格日志方法 ==================
    private static final String VS_BLUE = "\033[38;5;33m";    // VSCode信息蓝
    private static final String VS_GREEN = "\033[38;5;72m";   // VSCode成功绿
    private static final String VS_YELLOW = "\033[38;5;185m"; // VSCode警告黄
    private static final String VS_PURPLE = "\033[38;5;177m"; // VSCode高亮紫
    private static final String VS_CYAN = "\033[38;5;80m";   // VSCode代码青
    private static final String VS_RESET = "\033[0m";

    // VSCode风格日志方法 (全新实现)
    public static void vsInfo(String message) {
        System.out.printf(VS_BLUE + "[ℹ️] %s" + VS_RESET + "%n", message);
    }

    public static void vsSuccess(String message) {
        System.out.printf(VS_GREEN + "[✓] %s" + VS_RESET + "%n", message);
    }

    public static void vsWarning(String message) {
        System.out.printf(VS_YELLOW + "[⚠] %s" + VS_RESET + "%n", message);
    }

    public static void vsHighlight(String message) {
        System.out.printf(VS_PURPLE + "[➤] %s" + VS_RESET + "%n", message);
    }

    public static void vsCodeLog(String message) {
        System.out.printf(VS_CYAN + "[</>] %s" + VS_RESET + "%n", message);
    }

    // 特殊VS效果方法
    public static void vsBanner(String title) {
        // 创建与标题长度匹配的等号线
        StringBuilder lineBuilder = new StringBuilder();
        int length = title.length() + 4;  // [ + 空格 + title + 空格 + ] = 4个额外字符
        for (int i = 0; i < length; i++) {
            lineBuilder.append('=');
        }
        String line = lineBuilder.toString();

        // 输出带VSCode风格的分隔线
        System.out.println(
                VS_BLUE + line + VS_RESET + "\n" +
                        VS_CYAN + "[ " + title + " ]" + VS_RESET + "\n" +
                        VS_BLUE + line + VS_RESET
        );
    }

    public static void vsStatus(String emoji, String statusType, String message) {
        String color = VS_BLUE;
        switch(statusType.toLowerCase()) {
            case "success": color = VS_GREEN; break;
            case "warning": color = VS_YELLOW; break;
            case "highlight": color = VS_PURPLE; break;
            case "code": color = VS_CYAN; break;
        }
        System.out.println(color + emoji + " [" + statusType + "] " + message + VS_RESET);
    }

    // ================ 支持动态时间的VSCode风格方法 ================
    private static final String VSCODE_STATUS_BLOCK_BG = "\033[48;5;28m";  // VSCode深绿色背景
    private static final String VSCODE_STATUS_BLOCK_FG = "\033[97m";       // 白色文字
    private static final String VSCODE_STATUS_BLOCK_RESET = "\033[0m";
    private static final String VSCODE_SUCCESS_FG = "\033[38;5;41m";      // VSCode翠绿色文字

    /**
     * 打印XML重载成功消息（支持动态时间显示）
     *
     * @param reloadTime 重载所花费的时间（毫秒）
     */
    public static void vscodeXmlReloadedSuccess(long reloadTime) {
        // 左侧状态块内容
        String statusBlock = VSCODE_STATUS_BLOCK_BG + VSCODE_STATUS_BLOCK_FG + " RELOADED " + VSCODE_STATUS_BLOCK_RESET;

        // 右侧信息内容
        String message = VSCODE_SUCCESS_FG + "XML file reloaded successfully";

        // 添加动态时间
        String timeInfo = formatTime(reloadTime);

        System.out.println(statusBlock + " " + message);
        System.out.println(VSCODE_SUCCESS_FG + "  ↳ " + timeInfo + VSCODE_STATUS_BLOCK_RESET);
    }

    /**
     * 通用的VSCode状态信息打印（支持动态时间）
     *
     * @param statusType 状态类型（显示在左侧绿色块中）
     * @param message 显示在右侧的消息内容
     * @param duration 操作所花费的时间（毫秒）
     */
    public static void vscodeStatusWithDuration(String statusType, String message, long duration) {
        // 确保状态文本格式正确
        String formattedStatus = " " + statusType.trim().toUpperCase() + " ";

        // 左侧状态块
        String statusBlock = VSCODE_STATUS_BLOCK_BG + VSCODE_STATUS_BLOCK_FG + formattedStatus + VSCODE_STATUS_BLOCK_RESET;

        // 右侧信息
        String formattedMessage = VSCODE_SUCCESS_FG + message;

        // 格式化时间信息
        String timeInfo = formatTime(duration);

        System.out.println(statusBlock + " " + formattedMessage);
        System.out.println(VSCODE_SUCCESS_FG + "  ↳ " + timeInfo + VSCODE_STATUS_BLOCK_RESET);
    }

    /**
     * 格式化时间显示（自动选择最佳单位）
     *
     * @param millis 时间（毫秒）
     * @return 格式化后的时间字符串
     */
    private static String formatTime(long millis) {
        if (millis < 1000) {
            return millis + "ms";
        } else if (millis < 60000) {
            double seconds = millis / 1000.0;
            return String.format("%.2fs", seconds);
        } else {
            long minutes = millis / 60000;
            long seconds = (millis % 60000) / 1000;
            return String.format("%d分%02d秒", minutes, seconds);
        }
    }

    /**
     * 打印类似第二张图底部的纯成功消息（支持动态时间）
     *
     * @param message 要显示的成功消息
     * @param duration 操作所花费的时间（毫秒）
     */
    public static void vscodeSuccessWithDuration(String message, long duration) {
        String timeInfo = formatTime(duration);
        System.out.println(VSCODE_SUCCESS_FG + message);
        System.out.println(VSCODE_SUCCESS_FG + "  ↳ " + timeInfo + VSCODE_STATUS_BLOCK_RESET);
    }

    // 在ColorLogger类中添加以下方法
    public static void printOrmStartupBanner(String version, String jdbcUrl, long startupTime) {
        // 常量定义
        final String VSCODE_STATUS_BLOCK_BG = "\033[48;5;28m";  // VSCode深绿色背景
        final String VSCODE_STATUS_BLOCK_FG = "\033[97m";       // 白色文字
        final String VSCODE_SUCCESS_FG = "\033[38;5;41m";      // VSCode翠绿色文字
        final String VS_RESET = "\033[0m";
        final String ORM_HIGHLIGHT = "\033[38;5;219m";         // 框架名高亮色
        final String DB_HIGHLIGHT = "\033[38;5;117m";           // 数据库高亮色

        // 横幅顶部
        String header = VSCODE_STATUS_BLOCK_BG + VSCODE_STATUS_BLOCK_FG
                + " SPeed ORM INITIALIZED " + VS_RESET;

        // 框架信息块
        String ormInfo = ORM_HIGHLIGHT + "🚀 SPeed ORM " + version
                + " | " + GEAR + " Lightweight Java ORM" + VS_RESET;

        // 数据库连接信息
        String dbInfo = DB_HIGHLIGHT + LOCK + " Connected to: "
                + jdbcUrl + VS_RESET;

        // 性能指示器
        String performance = VSCODE_SUCCESS_FG + LIGHTNING + " Performance optimized"
                + " | " + FIRE + " Zero reflection overhead" + VS_RESET;

        // 动态时间显示
        String timeInfo = formatTime(startupTime);
        String timeLine = VSCODE_SUCCESS_FG + "  ↳ Initialized in " + timeInfo + VS_RESET;

        // 分隔线
        String separatorLine = DB_HIGHLIGHT + repeatChar('─', 60) + VS_RESET;

        // 组装输出
        String banner = String.format(
                "%s\n" +
                        "   %s\n" +
                        "   %s\n" +
                        "   %s\n" +
                        "   %s\n" +
                        "   %s",
                header, ormInfo, dbInfo, separatorLine, performance, timeLine
        );

        System.out.println(banner);
    }

    /**
     * 打印精简的多数据源启动横幅
     *
     * @param version      ORM版本
     * @param dataSources  数据源列表
     * @param startupTime  启动时间（毫秒）
     */
    public static void printMultiDataSourceBanner(String version,
                                                  List<DataSourceContextHolder.DataSourceInfo> dataSources,
                                                  long startupTime) {
        // 常量定义
        final String VSCODE_STATUS_BLOCK_BG = "\033[48;5;28m";  // VSCode深绿色背景
        final String VSCODE_STATUS_BLOCK_FG = "\033[97m";       // 白色文字
        final String ORM_HIGHLIGHT = "\033[38;5;219m";         // 框架名高亮色
        final String DB_HIGHLIGHT = "\033[38;5;117m";           // 数据库高亮色
        final String VSCODE_SUCCESS_FG = "\033[38;5;41m";      // VSCode翠绿色文字
        final String RESET = "\033[0m";

        // 横幅顶部
        String header = VSCODE_STATUS_BLOCK_BG + VSCODE_STATUS_BLOCK_FG
                + " SPeed ORM INITIALIZED " + RESET;

        // 框架信息块
        String ormInfo = ORM_HIGHLIGHT + "🚀 SPeed ORM " + version
                + " | " + GEAR + " Lightweight Java ORM" + RESET;

        // 主从数据库信息
        String masterCount = dataSources.stream()
                .filter(ds -> "master".equals(ds.getType()))
                .count() + " masters";

        String slaveCount = dataSources.stream()
                .filter(ds -> "slave".equals(ds.getType()))
                .count() + " slaves";

        String dbSummary = DB_HIGHLIGHT + LOCK + " Connected to "
                + dataSources.size() + " data sources ("
                + masterCount + ", "
                + slaveCount + ")" + RESET;

        // 构建每个数据源的简单信息
        StringBuilder dataSourcesInfo = new StringBuilder();
        for (int i = 0; i < dataSources.size(); i++) {
            DataSourceContextHolder.DataSourceInfo ds = dataSources.get(i);

            String icon = "Master".equals(ds.getType()) ? "👑" : "📖"; // 主库用王冠，从库用书本
            String driverIcon = getDriverIcon(ds.getDriverClassName());
            String color = "Master".equals(ds.getType()) ? ORM_HIGHLIGHT : DB_HIGHLIGHT;

            String dsLine = color + "   " + icon + " " + driverIcon + " "
                    + ds.getName() + " (" + ds.getType() + ")" + RESET;

            dataSourcesInfo.append(dsLine).append("\n");
        }

        // 性能信息
        String performance = VSCODE_SUCCESS_FG + LIGHTNING + " Performance optimized"
                + " | " + FIRE + " Zero reflection overhead" + RESET;

        // 时间信息
        String timeInfo = formatTime(startupTime);
        String timeLine = VSCODE_SUCCESS_FG + "  ↳ Initialized in " + timeInfo + RESET;

        // 分隔线（保留原有风格）
        String separatorLine = DB_HIGHLIGHT + repeatChar('─', 60) + RESET;

        // 组装输出
        String banner = String.format(
                "%s\n" +
                        "   %s\n" +
                        "   %s\n" +
                        "%s\n" +      // 数据源信息（多行）
                        "   %s\n" +
                        "   %s\n" +
                        "   %s",
                header, ormInfo, dbSummary, dataSourcesInfo.toString(),
                separatorLine, performance, timeLine
        );

        System.out.println(banner);
    }

    // 根据驱动类型获取图标
    private static String getDriverIcon(String driver) {
        if (driver == null) return "";

        if (driver.toLowerCase().contains("mysql")) {
            return "🐬"; // MySQL 海豚图标
        } else if (driver.toLowerCase().contains("postgres")) {
            return "🐘"; // PostgreSQL 大象图标
        } else if (driver.toLowerCase().contains("sqlserver")) {
            return "🪟"; // SQL Server 窗口图标
        } else if (driver.toLowerCase().contains("oracle")) {
            return "🔮"; // Oracle 水晶球图标
        } else if (driver.toLowerCase().contains("h2")) {
            return "🔰"; // H2 新手指图标
        } else {
            return "💾"; // 默认数据库图标
        }
    }

    // 在ColorLogger类中添加以下方法
    public static void printSpeedOrmBanner(String version, String jdbcUrl, long startupTime) {
        // 定义边框常量
        final String VSCODE_STATUS_BLOCK_BG = "\033[48;5;28m";  // VSCode深绿色背景
        final String VSCODE_STATUS_BLOCK_FG = "\033[97m";       // 白色文字
        final String BANNER_BORDER = "\033[38;5;34m";          // 边框绿色
        final String ORM_HIGHLIGHT = "\033[38;5;219m";         // 框架名高亮色
        final String DB_HIGHLIGHT = "\033[38;5;117m";           // 数据库高亮色
        final String VS_RESET = "\033[0m";

        // 横幅顶部边框（带角标）
        String topBorder = BANNER_BORDER + "╔" + repeatChar('═', 46) + "╗" + VS_RESET;

        // 横幅底部边框（带角标）
        String bottomBorder = BANNER_BORDER + "╚" + repeatChar('═', 46) + "╝" + VS_RESET;

        // 主标题（带绿色背景框）
        String titleBlock = BANNER_BORDER + "║ " + VS_RESET
                + VSCODE_STATUS_BLOCK_BG + VSCODE_STATUS_BLOCK_FG
                + "   SPeed ORM INITIALIZED   "
                + VS_RESET + BANNER_BORDER + " ║" + VS_RESET;

        // 版本信息
        String versionInfo = BANNER_BORDER + "║ " + VS_RESET
                + ORM_HIGHLIGHT + "🚀 Version: " + version
                + "  ⚡ Lightweight ORM" + VS_RESET
                + BANNER_BORDER + " ║" + VS_RESET;

        // 数据库连接信息
        String dbInfo = BANNER_BORDER + "║ " + VS_RESET
                + DB_HIGHLIGHT + "🔒 Database: " + jdbcUrl + VS_RESET
                + BANNER_BORDER + " ║" + VS_RESET;

        // 性能信息
        String timeInfo = formatTime(startupTime);
        String performance = BANNER_BORDER + "║ " + VS_RESET
                + ORM_HIGHLIGHT + "⚡ Performance: " + timeInfo
                + "  🔥 Zero reflection" + VS_RESET
                + BANNER_BORDER + " ║" + VS_RESET;

        // 空行（保持边框结构）
        String emptyLine = BANNER_BORDER + "║" + repeatChar(' ', 46) + "║" + VS_RESET;

        // 组装输出
        String banner = String.format(
                "%s\n" +
                        "%s\n" +
                        "%s\n" +
                        "%s\n" +
                        "%s\n" +
                        "%s\n" +
                        "%s\n" +
                        "%s",
                topBorder,
                emptyLine,
                titleBlock,
                versionInfo,
                dbInfo,
                performance,
                emptyLine,
                bottomBorder
        );

        System.out.println(banner);
    }

    public static void printSpeedOrmSuccessBanner(String version, long startupTime) {
        // 定义颜色常量 (匹配图片风格)
        final String DARK_BORDER = "\033[38;5;34m";           // 深绿色边框
        final String TITLE_COLOR = "\033[48;5;28;97m";        // 标题背景色
        final String ORM_HIGHLIGHT = "\033[38;5;219m";        // 框架名高亮色
        final String SUCCESS_COLOR = "\033[38;5;41m";         // 成功提示色
        final String RESET = "\033[0m";

        // 横幅顶部边框
        String topBorder = DARK_BORDER + "╔══════════════════════════════════════════════╗" + RESET;

        // 空行
        String emptyLine = DARK_BORDER + "║                                              ║" + RESET;

        // 标题行 - 修改为成功标志 ✅
        String title = DARK_BORDER + "║ " + RESET
                + TITLE_COLOR + "   ✅ SPeed ORM STARTED SUCCESSFULLY   " + RESET
                + DARK_BORDER + " ║" + RESET;

        // 版本信息（带图标）
        String versionInfo = DARK_BORDER + "║ " + RESET
                + ORM_HIGHLIGHT + "🚀 Version: " + version
                + " | ⚡ Lightweight ORM" + RESET
                + DARK_BORDER + " ║" + RESET;

        // 新特性显示（移除URL后添加）
        String features = DARK_BORDER + "║ " + RESET
                + SUCCESS_COLOR + "✔️ fast mode "
                + " | 🔐 Secure by design" + RESET
                + DARK_BORDER + " ║" + RESET;

        // 性能信息（带图标）
        String performance = DARK_BORDER + "║ " + RESET
                + ORM_HIGHLIGHT + "⚡ Initialized in " + formatTime(startupTime)
                + " | 🧠 AI Optimized" + RESET
                + DARK_BORDER + " ║" + RESET;

        // 横幅底部边框
        String bottomBorder = DARK_BORDER + "╚══════════════════════════════════════════════╝" + RESET;

        // 组装横幅
        System.out.println("\n" + topBorder);
        System.out.println(emptyLine);
        System.out.println(title);
        System.out.println(versionInfo);
        System.out.println(features);
        System.out.println(performance);
        System.out.println(emptyLine);
        System.out.println(bottomBorder + "\n");
    }

    // 辅助方法：重复字符
    private static String repeatChar(char c, int count) {
        return new String(new char[count]).replace('\0', c);
    }

}